package com.example.seakdreamandroid;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;

import com.example.seakdreamandroid.entity.AudioInfo;
import com.example.seakdreamandroid.entity.Favorite;
import com.example.seakdreamandroid.entity.Result;
import com.example.seakdreamandroid.entity.User;
import com.example.seakdreamandroid.whiteNoisePlayer.WhiteNoisePlayerActivity;
import com.example.seakdreamandroid.whiteNoisePlayer.WhiteNoisePlayerService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class FavoriteActivity extends AppCompatActivity {

    private final int REFRESH = 1;
    private FavoriteAdapter favoriteAdapter;
    private ImageButton returnF;
    private ListView listView;
    private SmartRefreshLayout smartRefreshLayout;
//    private List<AudioInfo> dataList = new ArrayList<>();
    private List<Favorite> dataList = new ArrayList<>();
    User user;
    private Handler myHandler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //处理消息
            switch (msg.what){
                case REFRESH:
                    //刷新ListView
                    favoriteAdapter.notifyDataSetChanged();
                    //结束刷新和加载的动画
                    smartRefreshLayout.finishRefresh();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_favorite);
        user = (User) getApplication();
        initView();
        getDataW();
        setListener();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Favorite favorite = dataList.get(position);
                if (favorite.getIsWhite() == 1){
                    List<AudioInfo> audioInfos = new ArrayList<>();
                    if (favorite.getWhiteId1() != null){
                        AudioInfo audioInfo = new AudioInfo();
                        audioInfo.setAudioId(favorite.getWhiteId1());
                        audioInfo.setAudioName(favorite.getWhiteName1());
                        audioInfo.setAudioPic(favorite.getWhitePic1());
                        audioInfo.setAudioUrl(favorite.getWhiteUrl1());
                        audioInfos.add(audioInfo);
                    }
                    if (favorite.getWhiteId2() != null){
                        AudioInfo audioInfo = new AudioInfo();
                        audioInfo.setAudioId(favorite.getWhiteId2());
                        audioInfo.setAudioName(favorite.getWhiteName2());
                        audioInfo.setAudioPic(favorite.getWhitePic2());
                        audioInfo.setAudioUrl(favorite.getWhiteUrl2());
                        audioInfos.add(audioInfo);
                    }
                    if (favorite.getWhiteId3() != null){
                        AudioInfo audioInfo = new AudioInfo();
                        audioInfo.setAudioId(favorite.getWhiteId3());
                        audioInfo.setAudioName(favorite.getWhiteName3());
                        audioInfo.setAudioPic(favorite.getWhitePic3());
                        audioInfo.setAudioUrl(favorite.getWhiteUrl3());
                        audioInfos.add(audioInfo);
                    }
                    //发送消息，播放
                    WhiteNoisePlayerService.getController().play(audioInfos,"PlayHistory",null,true);
                    //跳转
                    Intent intent = new Intent(FavoriteActivity.this, WhiteNoisePlayerActivity.class);
                    startActivity(intent);
                }else{
                    getAudio(favorite.getAudioId());
                }

            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        getDataW();
        //更新界面
        Message message = new Message();
        message.what = REFRESH;
        myHandler.sendMessage(message);
    }

    private void setListener(){
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                //下拉刷新时回调，请求最新数据
                getDataW();
            }
        });
        returnF.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initView(){
        listView = findViewById(R.id.list);
        favoriteAdapter = new FavoriteAdapter(
                this,
                dataList,
                R.layout.favorate_item
        );
        listView.setAdapter(favoriteAdapter);
        smartRefreshLayout = findViewById(R.id.srl);
        returnF = findViewById(R.id.return_f);
    }

    //请求数据
//    private void getData(){
//        OkHttpClient okHttpClient = new OkHttpClient();
//        Request request = new Request.Builder()
//                .url(Constant.BASE_URL + "AudioInfo/queryFavorite?userId=" + user.getUserId())
//                .build();
//        Call call = okHttpClient.newCall(request);
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                Log.i("okhttp", "请求失败");
//                e.printStackTrace();
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                String str = response.body().string();
//                Gson gson = new Gson();
//                Result result = gson.fromJson(str, new TypeToken<Result<List<AudioInfo>>>(){}.getType());
//                List<AudioInfo> audioInfo = (List<AudioInfo>) result.getData();
//                //Log.i("返回", audioInfo.get(0) + "");
//                dataList.clear();
////                dataList.addAll(audioInfo);
//                //更新界面
//                Message message = new Message();
//                message.what = REFRESH;
//                myHandler.sendMessage(message);
//            }
//        });
//    }

    //请求数据
    private void getDataW(){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "AudioInfo/queryFavoriteW?userId=" + user.getUserId())
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("okhttp", "请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                Gson gson = new Gson();
                Result result = gson.fromJson(str, new TypeToken<Result<List<Favorite>>>(){}.getType());
                List<Favorite> audioInfo = (List<Favorite>) result.getData();
                //Log.i("返回", audioInfo.get(0) + "");
                dataList.clear();
                dataList.addAll(audioInfo);
                //更新界面
                Message message = new Message();
                message.what = REFRESH;
                myHandler.sendMessage(message);
            }
        });
    }

    private void getAudio(String id){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "AudioInfo/findAudioInfoById?audioId=" + id)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("okhttp", "请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                try {
                    JSONObject result = new JSONObject(str);
                    Log.i("aaa", result.toString());
                    JSONObject favorite = result.getJSONObject("data");
                    Intent intent = new Intent();
                    intent.putExtra("audioUrl", favorite.getString("audioUrl"));
                    intent.putExtra("audioId", favorite.getString("audioId"));
                    intent.putExtra("audioName", favorite.getString("audioName"));
                    intent.putExtra("audioAuthor", favorite.getString("audioAuthor"));
                    intent.setClass(FavoriteActivity.this, MusicStoryPlayerActivity.class);
                    startActivity(intent);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getWhite(String id){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "AudioInfo/findAudioInfoById?audioId=" + id)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.i("okhttp", "请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                try {
                    JSONObject result = new JSONObject(str);
                    JSONObject favorite = result.getJSONObject("data");
                    AudioInfo audioInfo = new AudioInfo();
                    audioInfo.setAudioId(favorite.getString("audioId"));
                    audioInfo.setAudioUrl(favorite.getString("audioUrl"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}